<?php
include("connect.php");
$bookid = "";
$sql = "SELECT book_id FROM m_book";
$sql .= " WHERE ";

$type = $_REQUEST["type"];
if($type =='edit')
{
	$title=$_REQUEST["title"];
	$author = $_REQUEST["author"];
	$price = $_REQUEST["price"];
	$bookid = $_REQUEST["bookid"];
	$requestbookid = $_REQUEST["requestbookid"];
	//tunggu auto dari lauren
	$sql = "update T_REQUEST_BOOK set price=".$price." where request_book_id=".$requestbookid;
	mysql_query($sql);
	$sql = "update M_BOOK set book_title = '".$title."', book_author='".$author."' where book_id =".$bookid;
	mysql_query($sql);
	
	
?>
<script type="text/javascript">
<!--
alert("Your edit is successful!");
window.location = "my_request.php"
//-->
</script>
<?php	
	
}
if(isset($_REQUEST["title"]))
{
	$title = $_REQUEST["title"];
	$sql .= " book_title LIKE '%" .$title ."%'";
}
if(isset($_REQUEST["author"]))
{
	$author = $_REQUEST["author"];
	$sql .= " AND book_author LIKE '%" .$author ."%'";
}

$retval = mysql_query($sql, $con);
if (!$retval)
{
	echo $sql;
	die('Could not execute query: ' . mysql_error());
}
while($row = mysql_fetch_array($retval))
{
	$bookid = $row['book_id'];
}

if ($bookid != "")
{
	//if the book that the user request is already in the database
	$sql = "INSERT INTO t_request_book (user_id, book_id, is_get)";
	$sql .= " VALUES (".$_SESSION["userid"].", ".$bookid.", 0)";
	$retval = mysql_query($sql, $con);
	if (!$retval)
	{
		echo $sql;
		die('Insert data into Request Book Table error: ' . mysql_error());
	}
}
else
{
	//because of the book that the user request is not in the database
	//the data has to be inserted first into the database (to get the book id)
	$sql = "INSERT INTO m_book (book_title, book_author)";
	$sql .= " VALUES ('".$title."', '".$author."')";
	
	
	
	//retrieving the book_id for the book that has just been inserted
	$sql = "SELECT book_id FROM m_book";
	$sql .= " WHERE book_title LIKE '%" .$title ."%' AND book_author LIKE '%" .$author ."%'";
	$retval = mysql_query($sql, $con);
	if (!$retval)
	{
		echo $sql;
		die('Could not execute query: ' . mysql_error());
	}
	while($row = mysql_fetch_array($retval))
	{
		$bookid = $row['book_id'];
	}
	
	//then the request will be inserted into the t_request_book table
	$sql = "INSERT INTO t_request_book (user_id, book_id, is_get)";
	$sql .= " VALUES (".$_SESSION["userid"].", ".$bookid.", 0)";
	$retval = mysql_query($sql, $con);
	
}
?>
<script type="text/javascript">
<!--
alert('Your request is successful!');
window.location = "my_request.php"
//-->
</script>
